package cn.wen.bases.service.security;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;

import cn.wen.bases.service.BaseService;
import cn.wen.javax.security.IUser;
import cn.wen.javax.servlet.XRequest;
import cn.wen.javax.servlet.http.TokenOfWeb;

/**
 * Title: 用户服务
 * <p>
 * Description:
 * <p>
 * Copyright: Copyright (c) 2010-2012
 * 
 * @author <a href="mailto:ct_wen@qq.com">ctwen</a>, 温承瑭
 * @version Revision：1.0 Date：2012/3/21 Description：初完成。
 *          <P>
 */
public class UserService extends BaseService {

    /**
     * 验证用户。
     * 
     * @param request HttpServletRequest
     * @return 若验证通过，返回完整的用户实体；否则返回Null。
     */
    public IUser isVerified(HttpServletRequest request) {
	XRequest xRequest = new XRequest(request);

	IUser user = userFactory.newUser();
	String val = null;
	msg = "登录名或密码不能为空。";

	if (StringUtils.isBlank(val = (String) getValue(xRequest, "loginId"))) return null;
	user.setLoginId(val); // 登录ID

	if (StringUtils.isBlank(val = (String) getValue(xRequest, "password"))) return null;
	user.setPassword(val); // 密码

	user = userFactory.query(user);
	if (null == user) 
	    msg = "验证失败，您输入的密码和登录名不匹配，请重新输入。";
	else
	    msg = "欢迎您登录，" + user.getName() + "。";
	return user;
    }
    
    /**
     * 用户登录，成功后将完整的用户实体加入Session并返回；
     * 
     * @param request HttpServletRequest
     * @return 若验证通过，返回完整的用户实体；否则返回Null。
     */
    public IUser login(HttpServletRequest request) {
	IUser user = isVerified(request);
	if (null != user) request.getSession(true).setAttribute(TokenOfWeb.LOGGED_USER_TOKEN, user);
	return user;
    }

    private Object getValue(XRequest request, String key) {
	if (null != request.getValue(key)) return request.getValue(key);
	return request.getValue("user." + key);
    }

    private String msg;
    
    private UserFactory userFactory;

    public String getMessage() {
	return msg;
    }

    public void setUserFactory(UserFactory userFactory) {
        this.userFactory = userFactory;
    }

}
